from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler

# 1.获取数据集
iris = load_iris()

# 2.数据预处理
# 2.1数据分割
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)

# 3.特征工程
# 3.1 实例化一个转换器
transfer = StandardScaler()
# 调用fit_transform()方法
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)

# 3.机器学习(模型训练)
# 4.实例化1个估计器
estimator = KNeighborsClassifier(n_neighbors=5)

# 4.2调用交叉验证网格搜索模型
param_grid = {'n_neighbors': [1, 3, 5, 7, 9]}  # 必须跟算法里的参数(n_neighbors)一样
# cv表示几折交叉验证
estimator = GridSearchCV(estimator=estimator, param_grid=param_grid, cv=10, n_jobs=-1)

# 模型训练
estimator.fit(x_train, y_train)

# 5.模型预测
# 5.1 输出预测值
y_pre = estimator.predict(x_test)
print('预测值是:\n', y_pre)
print('预测值和真实值对比:\n', y_pre == y_test)

# 5.2输出准确率
print('准确率是:\n', estimator.score(x_test, y_test))

# 其他评价指标
print('最好的模型:\n', estimator.best_estimator_)
print('最好的结果:\n', estimator.best_score_)
print('最好的模型结果:\n', estimator.cv_results_)